package list

import (
	"fmt"
	"github.com/gofiber/fiber/v2"
	"sg-backend/global"
	"sg-backend/logger"
	"sg-backend/model/user"
	"sg-backend/utils"
)

/*
 * 4
 * DELETE,删除请求，/api/user/list
 */

type deleteKey struct {
	Key []uint `json:"key"`
}

// DeleteUser 删除用户为禁用用户，不删除数据
func DeleteUser(ctx *fiber.Ctx) error {
	// 权限验证
	utils.CheckPermsByTag("UserList", global.AuthUser.UserId, "delete")

	var delForm deleteKey
	if err := ctx.BodyParser(&delForm); err != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": fmt.Sprintf("数据解释出错！%s", err),
		})
	}

	// 获取禁用的ID
	for _, v := range delForm.Key {
		delObj := user.User{Id: v}
		r := global.DB.First(&delObj)
		if r.Error != nil {
			return ctx.JSON(fiber.Map{
				"status":  "error",
				"message": fmt.Sprintf("传参错误！错误：%v", r.Error),
			})
		}

		// 禁用用户
		delObj.IsActive = false
		global.DB.Save(&delObj)

		// 写日志
		logger.DbInfo(global.AuthUser.Username, fmt.Sprintf("禁用用户成功！用户：%+v ", delObj.Username))
	}

	return ctx.JSON(fiber.Map{
		"status":  "done",
		"message": "删除成功！",
	})
}
